#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""多线程下载妹子网图片😍

使用threading
"""

import bs4
import requests
import urllib.request as ur

import threading

class LoadingThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        super(LoadingThread, self).__init__(*args, **kwargs)
        self.image_name = kwargs['args'][0]

    def start(self):
        print('开始下载图片 %s' % self.image_name)
        super(LoadingThread, self).start()

    def join(self):
        super(LoadingThread, self).join()
        print('完成下载图片 %s'% self.image_name)

    def run(self):
        try:
            print('正在努力加载图片 %s ...'% self.image_name)
            super(LoadingThread, self).run()
            print('存储图片 %s'% self.image_name)
        except:
            print('图片 %s 无法下载.' % self.image_name)


def load_image(url):
    response = requests.get(url)
    soup = bs4.BeautifulSoup(response.text, 'lxml')
    threads = []
    for k,a in enumerate(soup.find_all('img')):
        if a.has_attr('src'):
            image = a['src']
            # if not image.startswith('http'):
            #     image = url + image
            # suffix = image.split('.')[-1]
            threads.append(LoadingThread(target=ur.urlretrieve, args=(image, 'images/%d.%s' %(k, 'jpg'))))

    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

url = "https://www.meizitu.com"
load_image(url)
